//
//  ViewController.m
//  19-JSON网易
//
//  Created by dllo on 16/8/9.
//  Copyright © 2016年 LST. All rights reserved.
//

#import "ViewController.h"
#import "NewsTitle.h"
#import "LabelFlowLayout.h"
#import "MyCollectionViewCell.h"
@interface ViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, waterFlowLayoutDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *myCollectionView;
@property (nonatomic, strong)NSMutableArray<NewsTitle *> *newstitleArray;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _newstitleArray = [NSMutableArray array];
    LabelFlowLayout *title = (LabelFlowLayout *)self.myCollectionView.collectionViewLayout;
    title.delegate = self;
    [self handleData];
    _myCollectionView.backgroundColor = [UIColor whiteColor];
}
- (void)handleData {
   NSString *newsJSON = [[NSBundle mainBundle]pathForResource:@"news" ofType:@"JSON"];

    NSData *JSONData = [NSData dataWithContentsOfFile:newsJSON];
    // JSON解析
    NSError *error = nil;
   NSDictionary *newsTitleDic = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:&error];
    NSArray *list = newsTitleDic[@"tList"];
    for (NSDictionary *newTitle in list) {
        NewsTitle *news = [[NewsTitle alloc] initWithDic:newTitle];
        [_newstitleArray addObject:news];
    }
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout height:(CGFloat)height heightForItemAtIndexPath:(NSIndexPath *)indexPath {
    NewsTitle *news = _newstitleArray[indexPath.row];
    CGRect rect = [news.tname boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 40) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:17]} context:nil];
    CGFloat width = ceil(rect.size.width);
    return width;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _newstitleArray.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.label.text = [_newstitleArray[indexPath.row] tname];
    return cell;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
